package pe.edu.upc.dew.grupo3a.web;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.context.support.WebApplicationContextUtils;

import pe.edu.upc.dew.grupo3a.model.Cliente;
import pe.edu.upc.dew.grupo3a.model.Funcion;
import pe.edu.upc.dew.grupo3a.model.Pelicula;
import pe.edu.upc.dew.grupo3a.model.Reserva;
import pe.edu.upc.dew.grupo3a.service.ClienteService;
import pe.edu.upc.dew.grupo3a.service.FuncionService;
import pe.edu.upc.dew.grupo3a.service.PeliculaService;
import pe.edu.upc.dew.grupo3a.service.ReservaService;
import pe.edu.upc.dew.grupo3a.service.SalaService;

/**
 * Servlet implementation class EntradasServLet
 */
public class EntradasServLet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private FuncionService funcionService;
	private PeliculaService peliculaService;
	private ReservaService reservaService;
	private ClienteService clienteService;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public EntradasServLet() {
        super();
        // TODO Auto-generated constructor stub
    }
    
	@Override
	public void init(ServletConfig config) throws ServletException	{
			this.peliculaService = WebApplicationContextUtils
			.getWebApplicationContext(config.getServletContext())
			.getBean("peliculaService", PeliculaService.class);
			//
//			this.salaService = WebApplicationContextUtils
//			.getWebApplicationContext(config.getServletContext())
//			.getBean("salaService", SalaService.class);
			//
			this.funcionService = WebApplicationContextUtils
			.getWebApplicationContext(config.getServletContext())
			.getBean("funcionService", FuncionService.class);
			//
			this.reservaService = WebApplicationContextUtils
			.getWebApplicationContext(config.getServletContext())
			.getBean("reservaService", ReservaService.class);
			//
			this.clienteService = WebApplicationContextUtils
			.getWebApplicationContext(config.getServletContext())
			.getBean("clienteService", ClienteService.class);
			
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String action = request.getParameter("accion");
		String codigoReserva =request.getParameter("codigoReserva");
		HttpSession session = request.getSession();

		if(action.equals("peliculachange")||action.equals("funcionchange")|| action.equals("buscar") ){
			try{
			String peliculaSelected = "";
			String funcionSelected = "";
			if(action.equals("buscar")){
				codigoReserva = request.getParameter("txt_CodSeparacion");
				Reserva reserva = null;
					reserva = reservaService.getReservaPorCodigo(codigoReserva);
					request.setAttribute("reserva", reserva);
					funcionSelected = reserva.getFuncion().getCodigofuncion();
					peliculaSelected = reserva.getFuncion().getPelicula().getNombre();
			}else{
				peliculaSelected = request.getParameter("peliculaSelected");
				funcionSelected = request.getParameter("funcionSelected");
			}
			List<Funcion> funciones = funcionService.getFuncionPorPelicula(peliculaSelected);
			request.setAttribute("peliculaSelected", peliculaSelected);
			request.setAttribute("funciones", funciones);
			if(funcionSelected.length()<=0) funcionSelected=funciones.get(0).getCodigofuncion();
			Funcion funcion = funcionService.getFuncionPorCodigo(funcionSelected);
			request.setAttribute("funcion", funcion);
			}catch(Exception ex){
			}
		} else if(action.equals("grabar")){
			//
			//
			SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
			String  codigofuncion = request.getParameter("cmb_Funciones");
			int entradas = Integer.parseInt(request.getParameter("txt_Entradas"));
			Double total = Double.parseDouble(request.getParameter("txt_Total"));
			Date fechaReserva = new Date(); 
			try {
				fechaReserva = dateFormat.parse(request.getParameter("dateIV"));
			} catch (ParseException e) {
			}
			String banco="BCP";
			String codigoDeposito = "";
			//
			Cliente  cliente = (Cliente) session.getAttribute("ClienteActivo");
			Funcion funcion = funcionService.getFuncionPorCodigo(codigofuncion);
			//
			Reserva reserva = new Reserva();
			reserva.setBanco(banco);
			reserva.setCliente(cliente);
			reserva.setCodigo(codigoReserva);
			reserva.setCodigoDeposito(codigoDeposito);
			reserva.setFechaReserva(fechaReserva);
			reserva.setFuncion(funcion);
			reserva.setNroEntradas(entradas);
			reserva.setTotal(total);
			//
			try {
				if(reservaService.getReservaPorCodigo(codigoReserva)!=null)
					reservaService.actualizarReserva(reserva);
				else codigoReserva = reservaService.insertarReserva(reserva);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		} 
		List<Pelicula> peliculasEstreno = peliculaService.getPeliculasPorEstado("Estreno");
		List<Pelicula> peliculasPorEstrenar = peliculaService.getPeliculasPorEstado("Proximamente");
		//
		request.setAttribute("codigoReserva", codigoReserva);
		request.setAttribute("peliculasEstreno", peliculasEstreno);
		request.setAttribute("peliculas", peliculasEstreno);
		request.setAttribute("peliculasPorEstrenar", peliculasPorEstrenar);
		request.setAttribute("accion", action);		
		request.getRequestDispatcher("entradas.jsp").forward(request,response);
	}

}
